import 'dart:convert';
import 'dart:math';
import 'package:base_flutter/base_flutter.dart';
import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/a_elder/models/elder_entity.dart';
import 'package:ls_work/a_elder/page/bed_change_history_page.dart';
import 'package:ls_work/a_elder/page/elder_grid_page.dart';
import 'package:ls_work/a_elder/page/elder_search_page.dart';
import 'package:ls_work/a_yyt/models/floor_list_entity.dart';
import 'package:ls_work/a_yyt/models/gean_entity.dart';
import 'package:ls_work/a_yyt/models/service_area_entity.dart';
import 'package:ls_work/a_yyt/models/staff_group_entity.dart';
import 'package:ls_work/common/common.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/res/resources.dart';
import 'package:ls_work/util/app_navigator.dart';
import 'package:gzx_dropdown_menu/gzx_dropdown_menu.dart';
import 'package:ls_work/util/event_bus.dart' as e;
import 'package:ls_work/util/toast.dart';
import 'package:ls_work/util/utils.dart';

import '../../model/building_model.dart';
import '../../widgets/out_line_button.dart';
import 'elder_info_page.dart';

class SortCondition {
  String? name;
  bool isSelected;

  SortCondition({this.name, this.isSelected = false});
}

class ElderPage extends StatefulWidget {
  @override
  _ElderPageState createState() => _ElderPageState();
}

class _ElderPageState extends State<ElderPage>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  PageController _pageController = PageController(initialPage: 0);
  TabController? _tabController;
  ElderEntity? _elderTotalCountModel;
  ElderEntity? _elderInCountModel;
  ElderEntity? _elderOutCountModel;

  List<String> _dropDownHeaderItemStrings = [
    '全部楼栋',
    '全部楼层',
    '筛选',
  ];
  List<ServiceAreaInfo> _buildingSortConditions = [];
  List<ServiceAreaInfo> _floorSortConditions = [];
  ServiceAreaInfo? _selectBuildingCondition;
  ServiceAreaInfo? _selectFloorSortCondition;
  GZXDropdownMenuController _dropdownMenuController =
  GZXDropdownMenuController();

  List<StaffGroupInfo> _nurseLevelList = [];
  List<StaffGroupInfo> _bodyTypeList = [];

  // List<ServiceAreaInfo> _floorList = [];

  var _scaffoldKey = new GlobalKey<ScaffoldState>();
  GlobalKey _stackKey = GlobalKey();
  double _ageBegainValue = 0.0;
  double _ageEndValue = 120.0;
  bool _sexManSelected = false;
  bool _sexWemanSelected = false;

  var buildingModel = BuildingModel();

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    _tabController = new TabController(vsync: this, length: 3);
    _getBuildingData();
    _fectNurseLevel();

    getOldData();



    ///1、自理；2、半自理；3、失能；4、失智'
    _bodyTypeList.add(StaffGroupInfo(name: '自理', id: 1, isSelected: false));
    _bodyTypeList.add(StaffGroupInfo(name: '半自理', id: 2, isSelected: false));
    _bodyTypeList.add(StaffGroupInfo(name: '失能', id: 3, isSelected: false));
    _bodyTypeList.add(StaffGroupInfo(name: '失智', id: 4, isSelected: false));
  }

  Future<void> _getBuildingData() async {
    await _fectBuildingList();
    e.eventBus.emit(Constant.eventElderFilter, [
      _selectBuildingCondition?.id??null,
      _selectFloorSortCondition?.id??null,
    ]);
  }

  @override
  void dispose() {
    _tabController?.dispose();
    _pageController.dispose();
    e.eventBus.off(Constant.eventElderFilter);
    e.eventBus.off(Constant.eventElderRightFilter);
    super.dispose();
  }

  _onPageChange(int index) {
    _tabController?.animateTo(index);
    Future.delayed(Duration(milliseconds: 200),(){
      e.eventBus.emit(Constant.eventElderFilter, [
        _selectBuildingCondition?.id,
        _selectFloorSortCondition?.id,
      ]);
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    return Scaffold(
      key: _scaffoldKey,
      backgroundColor: Colors.white,
      appBar: AppBar(
        elevation: 0.5,
        title: Text('长者'),
        centerTitle: true,
        actions: [
          IconButton(
            color: Colors.white,
            icon: Icon(
              Icons.search,
              size: 30,
              color: Colors.black,
            ),
            onPressed: () {
              AppNavigator.push(
                context,
                ElderSearchPage(isSelected: false),
              );
            },
          )
        ],
      ),
      body: Stack(
        key: _stackKey,
        children: [
          Column(
            children: [
              TabBar(
                onTap: (index) {
                  if (!mounted) {
                    return;
                  }
                  _pageController.jumpToPage(index);
                },
                isScrollable: false,
                controller: _tabController,
                labelStyle:
                TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                indicatorSize: TabBarIndicatorSize.label,
                unselectedLabelColor: Colours.text_gray,
                unselectedLabelStyle: TextStyles.textGray14,
                labelColor: Colours.text_dark,
                indicatorColor: Colours.app_main,
                indicatorPadding: EdgeInsets.only(bottom: 5),
                tabs: <Widget>[
                  Tab(
                    text: _elderTotalCountModel != null
                        ? '全部 ${_elderTotalCountModel?.total??0}'
                        : '全部',
                  ),
                  Tab(
                    text: _elderInCountModel != null
                        ? '在院 ${_elderInCountModel?.total??0}'
                        : '在院',
                  ),
                  Tab(
                    text: _elderOutCountModel != null
                        ? '请假 ${_elderOutCountModel?.total??0}'
                        : '请假',
                  ),
                ],
              ),
              GZXDropDownHeader(
                // 下拉的头部项，目前每一项，只能自定义显示的文字、图标、图标大小修改
                items: [
                  GZXDropDownHeaderItem(_dropDownHeaderItemStrings[0]),
                  GZXDropDownHeaderItem(_dropDownHeaderItemStrings[1]),
                  GZXDropDownHeaderItem(_dropDownHeaderItemStrings[2])
                  // iconData: Icons.filter_frames, iconSize: 18),
                ],
                // GZXDropDownHeader对应第一父级Stack的key
                stackKey: _stackKey,
                // controller用于控制menu的显示或隐藏
                controller: _dropdownMenuController,
//                // 头部的高度
                height: 50,
//                // 头部背景颜色
                color: Colours.bg_color,
//                // 头部边框颜色
                borderColor: Colours.bg_color,
                dividerHeight: 20,
                // ���割线颜色
                dividerColor: Colours.order_line,
                style: TextStyle(color: Color(0xFF666666), fontSize: 14),
//                // 下拉时文字样式
                dropDownStyle: TextStyle(
                  fontSize: 14,
                  color: Colours.app_main,
                ),
//                // 图标大小
//                iconSize: 20,
//                // 图标颜色
//                iconColor: Color(0xFFafada7),
//                // 下拉时图标颜色
                iconDropDownColor: Colours.app_main,
              ),
              Expanded(
                child: PageView.builder(
                  key: const Key('pageView'),
                  itemCount: 3,
                  onPageChanged: _onPageChange,
                  controller: _pageController,
                  itemBuilder: (BuildContext context, int index) {
                    switch (index) {
                      case 0:
                        return ElderGridPage();
                        break;
                      case 1:
                        return ElderGridPage(type: 0);
                        break;
                      case 2:
                        return ElderGridPage(type: 1);
                        break;
                      default:
                        return Container();
                    }
                  },
                ),
              ),
            ],
          ),
          // 下拉菜单
          GZXDropDownMenu(
            // controller用于控制menu的显示或隐藏
            controller: _dropdownMenuController,
            // 下拉菜单显示或隐藏动画时长
            animationMilliseconds: 300,
            // 下拉后遮罩颜色
//          maskColor: Theme.of(context).primaryColor.withOpacity(0.5),
//          maskColor: Colors.red.withOpacity(0.5),
            dropdownMenuChanging: (isShow, index) {
              setState(() {
                print('(正在${isShow ? '显示' : '隐藏'}$index)');
              });
            },
            dropdownMenuChanged: (isShow, index) {
              setState(() {
                print('(已经${isShow ? '显示' : '隐藏'}$index)');
              });
            },
            // 下拉菜单，高度自定义，你想显示什么就显示什么，完全由你决定，你只需要在选择后调用_dropdownMenuController.hide();即可
            menus: [

              GZXDropdownMenuBuilder(
                dropDownHeight: min(40.0 * _buildingSortConditions.length,
                    MediaQuery
                        .of(context)
                        .size
                        .height * 0.65),
                dropDownWidget:
                _buildingSortConditions.isEmpty?Container():_buildConditionListWidget(_buildingSortConditions, (value) {
                  _selectBuildingCondition = value;
                  _dropDownHeaderItemStrings[0] = _selectBuildingCondition?.name??"";
                  _dropdownMenuController.hide();
                  setState(() {
                    _setFloor();
                  });
                  e.eventBus.emit(Constant.eventElderFilter, [
                    value.id,
                    _selectFloorSortCondition?.id,
                  ]);
                }),
              ),
              GZXDropdownMenuBuilder(
                dropDownHeight: min(40.0 * _floorSortConditions.length,
                    MediaQuery
                        .of(context)
                        .size
                        .height * 0.65),
                dropDownWidget:
                _buildConditionListWidget(_floorSortConditions, (value) {
                  _selectFloorSortCondition = value;
                  _dropDownHeaderItemStrings[1] = _selectFloorSortCondition?.name??"";
                  _dropdownMenuController.hide();
                  e.eventBus.emit(Constant.eventElderFilter, [
                    _selectBuildingCondition?.id,
                    value.id,
                  ]);
                }),
              ),
              GZXDropdownMenuBuilder(
                dropDownHeight: ScreenUtil.getScreenH(context) * 2 / 3 - 100,
                dropDownWidget: _buildFiltWidget(),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildFiltWidget() {
    return StatefulBuilder(
      builder: (context, setDialogState) {
        return SingleChildScrollView(
          child: Container(
            padding: EdgeInsets.all(15),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Text(
                      '年龄   ',
                      style: TextStyles.textDark18,
                    ),
                    Text(
                      '${_ageBegainValue.floor()} - ${_ageEndValue.floor()}' +
                          "岁",
                      style: TextStyle(fontSize: 16, color: Colours.app_main),
                    ),
                  ],
                ),
                Gaps.vGap10,
                Row(
                  children: [
                    Text(
                      '0',
                      style: TextStyles.textGray14,
                    ),
                    Expanded(
                      child: RangeSlider(
                        min: 0,
                        max: 120,
                        divisions: 50,
                        labels: RangeLabels("${_ageBegainValue.floor()}",
                            "${_ageEndValue.floor()}"),
                        activeColor: Colors.blue,
                        inactiveColor: Colors.grey,
                        values: RangeValues(_ageBegainValue, _ageEndValue),
                        onChanged: (RangeValues values) {
                          //滑动时更新widget的状态值
                          // _rangeSlideChange(values.start, values.end);
                          setDialogState(() {
                            _ageBegainValue = values.start;
                            _ageEndValue = values.end;
                          });
                        },
                      ),
                    ),
                    Text(
                      '120',
                      style: TextStyles.textGray14,
                    ),
                  ],
                ),
                Gaps.vGap10,
                Text('性别', style: TextStyles.textDark16),
                Wrap(
                  spacing: 10,
                  children: [
                    ChoiceChip(
                      label: Text(
                        '男',
                        style: TextStyle(fontSize: 14, color: Colors.black),
                      ),
                      selected: _sexManSelected,
                      selectedColor: Colours.app_main,
                      onSelected: (value) {
                        setDialogState(() {
                          _sexManSelected = value;
                        });
                      },
                    ),
                    ChoiceChip(
                      label: Text(
                        '女',
                        style: TextStyle(fontSize: 14, color: Colors.black),
                      ),
                      selected: _sexWemanSelected,
                      selectedColor: Colours.app_main,
                      onSelected: (value) {
                        setDialogState(() {
                          _sexWemanSelected = value;
                        });
                      },
                    ),
                  ],
                ),
                Gaps.vGap10,
                Text('护理等级', style: TextStyles.textDark16),
                Wrap(
                  spacing: 5,
                  children: _nurseLevelList.map((e) {
                    return ChoiceChip(
                      label: Text('${e.name}'),
                      selected: e.isSelected==true,
                      selectedColor: Colours.app_main,
                      labelStyle: TextStyle(fontSize: 14, color: Colors.black),
                      onSelected: (value) {
                        setDialogState(() {
                          e.isSelected = value;
                        });
                      },
                    );
                  }).toList(),
                ),
                Gaps.vGap10,
                Text('身体状况', style: TextStyles.textDark16),
                Wrap(
                  spacing: 5,
                  children: _bodyTypeList.map((e) {
                    return ChoiceChip(
                      label: Text('${e.name}'),
                      selected: e.isSelected==true,
                      selectedColor: Colours.app_main,
                      labelStyle: TextStyle(fontSize: 14, color: Colors.black),
                      onSelected: (value) {
                        setDialogState(() {
                          e.isSelected = value;
                        });
                      },
                    );
                  }).toList(),
                ),
                Gaps.vGap10,
                Gaps.line,
                Gaps.vGap10,
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    OutlineButton(
                      onPressed: () {
                        setDialogState(() {
                          _ageBegainValue = 50.0;
                          _sexManSelected = false;
                          _sexWemanSelected = false;
                          for (var item in _nurseLevelList) {
                            item.isSelected = false;
                          }
                          for (var item in _bodyTypeList) {
                            item.isSelected = false;
                          }
                        });
                      },
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(20.0)),
                      child: Text(
                        '重置',
                        style: TextStyles.textDark16,
                      ),
                    ),
                    ElevatedButton(
                      style: ButtonStyle(
                        backgroundColor: WidgetStateProperty.all(Colors.blue),
                        shape: WidgetStateProperty.all(RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20.0))),
                      ),
                      child: Text("确定"),
                      onPressed: () {
                        e.eventBus.emit(Constant.eventElderRightFilter, [
                          _ageBegainValue,
                          _ageEndValue,
                          _sexManSelected,
                          _sexWemanSelected,
                          _nurseLevelList,
                          _bodyTypeList,
                        ]);
                        _dropdownMenuController.hide();
                      },
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  _buildConditionListWidget(items,
      void itemOnTap(ServiceAreaInfo sortCondition)) {
    return ListView.separated(
      shrinkWrap: true,
      scrollDirection: Axis.vertical,
      itemCount: items.length,
      // item 的个数
      separatorBuilder: (BuildContext context, int index) =>
          Divider(height: 1.0),
      // 添加分割线
      itemBuilder: (BuildContext context, int index) {
        ServiceAreaInfo goodsSortCondition = items[index];
        return GestureDetector(
          onTap: () {
            for (var value in items) {
              value.isSelected = false;
            }
            goodsSortCondition.isSelected = true;

            itemOnTap(goodsSortCondition);
          },
          child: Container(
            height: 40,
            child: Row(
              children: <Widget>[
                SizedBox(
                  width: 16,
                ),
                Expanded(
                  child: Text(
                    goodsSortCondition.name??"",
                    style: TextStyle(
                      color: goodsSortCondition.isSelected
                          ? Colours.app_main
                          : Colors.black,
                    ),
                  ),
                ),
                goodsSortCondition.isSelected
                    ? Icon(
                  Icons.check,
                  color: Colours.app_main,
                  size: 16,
                )
                    : SizedBox(),
                SizedBox(
                  width: 16,
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Future _fectElderCount(int type) async {
    Map<String, dynamic> params = Map();
    params["page"] = 1;
    params["rows"] = 20;
    if (type == 1 || type == 2) params["statusSecondId"] = type - 1;
    if (type == 2) {
      params["statusMasterId"] = 0;
      params['validSign'] = 1;
    }
    params["queryType"] = '2';
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.customerElder}?${requestParams(params)}')
        .then((r) {
      ///
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            ElderEntity model = ElderEntity.fromJson(map['data']);
            setState(() {
              switch (type) {
                case 0:
                  _elderTotalCountModel = model;
                  break;
                case 1:
                  _elderInCountModel = model;
                  break;
                case 2:
                  _elderOutCountModel = model;
                  break;
                default:
              }
            });
          }
        }
      } else {
        // view.showToast(r.statusCode.toString());
        // view.provider.setHasMore(false);
      }
    }).catchError((e) {
      print(e.toString());
      // view.provider.setHasMore(false);
      // view.showToast(getErrorMessage((e as DioError).type));
    });
  }

  Future _fectArwaData() async {
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.serviceAreaWrapperList}')
        .then((r) {
      ///
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            GeAnEntity model = GeAnEntity.fromJson(map['data']);
            if ((model.rows??[]).length > 0) {
              var list = (model.rows??[])
                  .map((e) =>
                  ServiceAreaInfo(
                    name: '${e.bean?.name??""}',
                    id: e.bean?.id,
                    isSelected: false,
                  ))
                  .toList();
              setState(() {
                list.sort((o1, o2) {
                  // var p1 = o1.name.replaceAll("号楼", "");
                  // var p2 = o2.name.replaceAll("号楼", "");
                  return o1.id!.compareTo(o2.id!);
                });
                _floorSortConditions = list;
                _floorSortConditions.first.isSelected = true;
                _selectFloorSortCondition = _floorSortConditions.first;
                _dropDownHeaderItemStrings[1] = _selectFloorSortCondition?.name??"";
                e.eventBus.emit(Constant.eventElderFilter, [
                  _selectBuildingCondition?.id,
                  _selectFloorSortCondition?.id,
                ]);
              });
              // setState(() {
              //   for (var item in model.rows) {
              //     _areaSortConditions.add(
              //       ServiceAreaInfo(
              //         name: '${item.bean.name}',
              //         id: item.bean.id,
              //         isSelected: false,
              //       ),
              //     );
              //   }
              // });
            } else {
              Toast.show("区域获取失败");
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  void getOldData() {
    _fectElderCount(0);
    _fectElderCount(1);
    _fectElderCount(2);
  }

  Future _fectNurseLevel() async {
    HttpUtil.instance.getDio().post(HttpApi.branchNurseLevel).then((r) {
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            StaffGroupEntity model = StaffGroupEntity.fromJson(map);
            if ((model.data??[]).length >= 0) {
              _nurseLevelList = (model.data??[]);
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  Future _fectBuildingList() async {
    try {
      var list = await buildingModel.getBuildingList();
        for (var item in list) {
          _buildingSortConditions.add(
            ServiceAreaInfo(
                name: '${item.buildingNo}',
                id: item.id,
                isSelected: false,
                floor: item.floorList
            ),
          );
        }
        setState(() {

         // if(_buildingSortConditions.isEmpty){
         //
         //
         // }
          _buildingSortConditions.insert(0, ServiceAreaInfo(name: '全部楼栋',floor: []));
         _buildingSortConditions[0].isSelected = true;
         _selectBuildingCondition = _buildingSortConditions[0];
         _dropDownHeaderItemStrings[0] = _buildingSortConditions[0].name??"";
         _setFloor();
        });

    } catch (e) {
      Toast.show(NetErrorUtils.getNetError(e));
    }
  }


  void _setFloor() {
    if (_selectBuildingCondition != null) {
     _floorSortConditions = (_selectBuildingCondition?.floor??[]).map((e) =>
          ServiceAreaInfo(
              name: e.floorNo, id: e.id, isSelected:
          false)).toList();

     _floorSortConditions
         .insert(0,ServiceAreaInfo(name: '全部楼层', id: 0, isSelected: true));
     _selectFloorSortCondition = _floorSortConditions[0];
     _dropDownHeaderItemStrings[1] = "全部楼层";
    }
  }
}
